<template>
	<view class="container" :style="{ paddingTop: (statusBarHeight + navBarHeight) + 'px' }">
		<!-- 自定义导航栏 - 小程序适配版本 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content"
				:style="{ height: navBarHeight + 'px', paddingRight: menuButtonInfo.width + menuButtonInfo.right - windowWidth + 10 + 'px' }">
				<view class="back-btn" @click="goBack">
					<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
				</view>
				<view class="search-wrapper">
					<view class="search-input-wrapper" @click="goToSearch">
						<image :src="serverAddress+'img/icon-search@2x.png'" class="search-icon"></image>
						<input type="text" value="搜索商品/商家" disabled />
					</view>
				</view>
			</view>
		</view>

		<!-- 筛选条件 -->
		<view class="filter-bar">
			<view :class="{active: currentFilter === 'comprehensive'}" @click="changeFilter('comprehensive')">
				<text>综合</text>
			</view>
			<view :class="{active: currentFilter === 'sales'}" @click="changeFilter('sales')">
				<text>销量</text>
			</view>
			<view :class="{active: currentFilter === 'price'}" @click="changePriceSort">
				<text>价格</text>
				<view class="price-sort-arrows">
					<view 
						class="arrow-up" 
						:class="{active: priceSort === 'asc'}"
					>▲</view>
					<view 
						class="arrow-down" 
						:class="{active: priceSort === 'desc'}"
					>▼</view>
				</view>
			</view>
			<view @click="openFilter" :class="{active: hasActiveFilter}">
				<text>筛选</text>
				<image :src="serverAddress+'img/icon-screen@2x.png'" class="filter-icon"></image>
			</view>
		</view>

		<!-- 商品列表容器 -->
		<view class="content">
			<!-- 无商品提示 -->
			<view v-if="!products.length && !loading" class="wu">
				<view>
					<image :src="serverAddress+'img/icon-No-goods.png'"></image>
				</view>
				<text>抱歉,没有找到您搜索的商品哦!</text>
			</view>
			
			<!-- 商品列表 -->
			<view class="sea_list" id="sea_list">
				<view class="displayflexa indexgoods">
					<view v-for="item in products" :key="item.id" class="product-link" @click="goToDetail(item.id)">
						<view class="seali_inf">
							<view class="inf_img" :style="`background:url(${imgUrl}${item.img}) no-repeat center center;background-size:3.54rem 2.92rem;`"></view>
							<view class="inf_con">
								<view class="font14 goods-name">{{item.goods_name}}</view>
								<view class="font12 rebate-info">分润<text>￥{{item.rebate_price}}</text></view>
								<view class="font12 price-info">￥<text class="font15">{{item.sale_price}}</text></view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载更多提示 -->
		<view v-if="loading" class="more font15">
			<text class="pull_icon"></text>
			<text>加载中...</text>
		</view>
		<view v-else-if="!hasMore && products.length > 0" class="more font15">
			<text>没有更多数据了</text>
		</view>

		<!-- 遮罩层 -->
		<view v-if="showFilter" class="mask" @click="closeFilter"></view>

		<!-- 筛选面板 -->
		<view 
			v-if="showFilter"
			class="filter-popup"
		>
			<view class="filter-panel">
				<view class="filter-header">
					<text class="filter-title">价格区间</text>
				</view>

				<view class="filter-content">
					<!-- 价格区间 -->
					<view class="filter-section">
						<view class="price-inputs">
							<input 
								v-model="priceMin" 
								placeholder="最低价" 
								type="number"
								class="price-input"
							/>
							<text class="price-separator">----</text>
							<input 
								v-model="priceMax" 
								placeholder="最高价" 
								type="number"
								class="price-input"
							/>
						</view>
					</view>

					<!-- 新品筛选 -->
					<view class="filter-section">
						<view class="section-title">新品</view>
						<view class="filter-options">
							<view 
								class="filter-option"
								:class="{active: selectedNew === '新品'}"
								@click="selectNew('新品')"
							>
								新品
							</view>
						</view>
					</view>

					<!-- 品牌筛选 -->
					<view class="filter-section">
						<view class="section-title">品牌</view>
						<view v-if="brandList.length > 6" class="brand-expand" @click="toggleBrandExpand">
							<text class="expand-text">{{brandExpanded ? '收起' : '展开'}}</text>
						</view>
						<view class="filter-options">
							<!-- 显示前6个品牌 -->
							<view 
								v-for="(brand, index) in displayBrands" 
								:key="brand.brand_id"
								class="filter-option"
								:class="{active: selectedBrandId === brand.brand_id}"
								@click="selectBrand(brand.name, brand.brand_id)"
							>
								{{brand.name}}
							</view>
							<!-- 展开后显示剩余品牌 -->
							<view 
								v-if="brandExpanded"
								v-for="brand in expandedBrands" 
								:key="brand.brand_id"
								class="filter-option"
								:class="{active: selectedBrandId === brand.brand_id}"
								@click="selectBrand(brand.name, brand.brand_id)"
							>
								{{brand.name}}
							</view>
						</view>
					</view>
				</view>

				<!-- 底部按钮 -->
				<view class="filter-footer">
					<view class="reset-btn" @click="resetFilter">
						重置
					</view>
					<view class="confirm-btn" @click="applyFilter">
						确定
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/index.js';
	import {
		inject
	} from 'vue'

	export default {
		data() {
			return {
				// 小程序适配相关
				statusBarHeight: 0,
				navBarHeight: 44,
				menuButtonInfo: {},
				windowWidth: 375,
				
				imgUrl: inject('$imgUrl'),
				serverAddress: inject('$serverAddress', ''),
				categoryId: '',
				level: '',
				products: [],
				currentFilter: 'comprehensive',
				priceSort: 'asc', // 价格排序方向：asc升序，desc降序
				showFilter: false,
				showRebateFilter: false, // 是否显示分润筛选
				priceMin: '',
				priceMax: '',
				selectedNew: '',
				selectedBrand: '',
				selectedBrandId: '',
				brandList: [], // 品牌列表
				brandExpanded: false,
				searchKeyword: '',
				page: 1,
				loading: false,
				hasMore: true,
				preventReclick: false, // 防止重复点击
				time: new Date().getTime()
			};
		},
		computed: {
			hasActiveFilter() {
				return this.priceMin || this.priceMax || this.selectedNew || this.selectedBrand;
			},
			// 显示的品牌列表（前6个）
			displayBrands() {
				return this.brandList.slice(0, 6);
			},
			// 展开后显示的品牌列表（第7个开始）
			expandedBrands() {
				return this.brandList.slice(6);
			}
		},
		
		onLoad(options) {
			this.initMiniProgramAdapt();
			this.categoryId = options.id || 0;
			this.level = options.level || 0;
			this.loadProducts();
		},
		
		onReachBottom() {
			if (!this.loading && this.hasMore) {
				this.page++;
				this.loadProducts();
			}
		},
		
		methods: {
			// 小程序适配初始化
			initMiniProgramAdapt() {
				// 获取系统信息
				const systemInfo = uni.getSystemInfoSync()
				this.statusBarHeight = systemInfo.statusBarHeight || 0
				this.windowWidth = systemInfo.windowWidth || 375

				// 获取胶囊按钮信息（仅小程序）
				// #ifdef MP
				try {
					this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
				} catch (e) {
					console.error('获取胶囊按钮信息失败:', e)
					this.menuButtonInfo = {
						width: 87,
						height: 32,
						top: this.statusBarHeight + 6,
						right: 7,
						bottom: this.statusBarHeight + 38,
						left: this.windowWidth - 94
					}
					this.navBarHeight = 44
				}
				// #endif

				// #ifndef MP
				this.menuButtonInfo = {
					width: 0,
					height: 0,
					top: 0,
					right: 0,
					bottom: 0,
					left: 0
				}
				this.navBarHeight = 44
				// #endif
			},
			
			loadProducts() {
				if (this.loading) return;
				
				this.loading = true;
				const params = {
					cate_id: this.categoryId,
					level: this.level,
					is_new: this.getIsNew(),
					brand: this.selectedBrandId,
					zt: this.getZt(),
					pages: this.page,
					sale_price: this.getPriceRange(),
					order: this.getOrder()
				};
				
				api.goodsApi.getGoodsList(params).then(res => {
					if (res.r === 0) {
						const goods = res.data.goods || [];
						if (this.page === 1) {
							this.products = goods;
						} else {
							this.products = this.products.concat(goods);
						}
						
						// 检查是否还有更多数据
						this.hasMore = goods.length > 0;
						
						// 如果没有商品且是第一页，显示无商品提示
						if (goods.length === 0 && this.page === 1) {
							// 无商品处理已在模板中处理
						}
					} else {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						});
					}
					this.loading = false;
				}).catch(err => {
					console.error('加载商品失败:', err);
					this.loading = false;
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				});
			},
			getZt() {
				if (this.currentFilter === 'comprehensive') return 'score_total';
				if (this.currentFilter === 'sales') return 'sales_num';
				if (this.currentFilter === 'rebate') return 'rebate_money';
				if (this.currentFilter === 'price') return 'sale_price';
				return 'score_total';
			},
			
			getPriceRange() {
				if (this.priceMin && this.priceMax) {
					return `${this.priceMin},${this.priceMax}`;
				}
				return '1,99999999999999';
			},
			
			getOrder() {
				if (this.currentFilter === 'price') {
					return this.priceSort === 'asc' ? 1 : 2; // 1为升序，2为降序
				}
				return 1;
			},
			
			getIsNew() {
				return this.selectedNew === '新品' ? 1 : 0;
			},
			changeFilter(filter) {
				this.currentFilter = filter;
				this.page = 1;
				this.products = [];
				this.loadProducts();
			},
			
			// 切换价格排序
			changePriceSort() {
				if (this.currentFilter === 'price') {
					// 如果已经是价格排序，则切换升序/降序
					this.priceSort = this.priceSort === 'asc' ? 'desc' : 'asc';
				} else {
					// 如果不是价格排序，则设置为价格排序并切换到降序（因为默认显示升序）
					this.currentFilter = 'price';
					this.priceSort = 'desc';
				}
				this.page = 1;
				this.products = [];
				this.loadProducts();
			},
			openFilter() {
				console.log('======openFilter=====')
				this.showFilter = true;
				// 加载品牌列表
				this.loadBrandList();
			},
			closeFilter() {
				this.showFilter = false;
			},
			selectNew(value) {
				this.selectedNew = this.selectedNew === value ? '' : value;
				console.log("======selected======",this.selectedNew)
			},
			selectBrand(value) {
				this.selectedBrand = this.selectedBrand === value ? '' : value;
			},
			toggleBrandExpand() {
				this.brandExpanded = !this.brandExpanded;
			},
			
			
			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/goods/detail?id=${id}`
				});
			},
			
			// 跳转到搜索页面
			goToSearch() {
				uni.navigateTo({
					url: '/pages/search/index'
				});
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
			// 获取品牌列表
			loadBrandList() {
				if (this.preventReclick) return;
				
				this.preventReclick = true;
				api.goodsApi.getFilterBrands({
					cate_id: this.categoryId,
					level: this.level
				}).then(res => {
					if (res.r === 0 && res.data.lists && res.data.lists.length > 0) {
						this.brandList = res.data.lists[0].lists || [];
					}
					this.preventReclick = false;
				}).catch(err => {
					console.error('获取品牌列表失败:', err);
					this.preventReclick = false;
				});
			},
			
			// 选择品牌
			selectBrand(brandName, brandId) {
				if (this.selectedBrand === brandName) {
					this.selectedBrand = '';
					this.selectedBrandId = '';
				} else {
					this.selectedBrand = brandName;
					this.selectedBrandId = brandId;
				}
			},
			
			// 重置筛选条件
			resetFilter() {
				this.priceMin = '';
				this.priceMax = '';
				this.selectedNew = '';
				this.selectedBrand = '';
				this.selectedBrandId = '';
				// 重新加载页面
				this.page = 1;
				this.products = [];
				this.loadProducts();
					this.showFilter = false;
			},
			
			// 应用筛选
			applyFilter() {
				this.showFilter = false;
				this.page = 1;
				this.products = [];
				this.loadProducts();
			},
			
			
			// 搜索方法
			onSearch() {
				this.page = 1;
				this.products = [];
				this.loadProducts();
			}
		}
	};
</script>

<style scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
	}

	/* 自定义导航栏 - 小程序适配版本 */
	.custom-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);
	}

	.navbar-content {
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		gap: 20rpx;
	}

	.back-btn {
		width: 44rpx;
		height: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.search-wrapper {
		flex: 0.67;
		max-width: 480rpx;
	}

	.search-input-wrapper {
		height: 56rpx;
		background-color: #ffffff;
		border-radius: 28rpx;
		display: flex;
		align-items: center;
		padding: 0 24rpx;
	}

	.search-icon {
		width: 28rpx;
		height: 28rpx;
		margin-right: 12rpx;
	}

	.search-input-wrapper input {
		flex: 1;
		font-size: 26rpx;
		color: #999;
		border: none;
		outline: none;
		background: transparent;
	}

	/* 筛选条件栏 */
	.filter-bar {
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 24rpx 0;
		background-color: white;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.filter-bar > view {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		color: #333;
		position: relative;
		cursor: pointer;
	}

	.filter-bar > view.active {
		color: #00c896;
	}

	.filter-bar > view.active text {
		color: #00c896;
	}

	/* 价格排序箭头样式 */
	.price-sort-arrows {
		display: flex;
		flex-direction: column;
		margin-left: 8rpx;
		line-height: 1;
	}

	.arrow-up, .arrow-down {
		font-size: 20rpx;
		color: #ccc;
		line-height: 1;
		transition: color 0.3s ease;
		transform: scaleY(0.6);
	}
	
	.arrow-down {
		margin-top: -6rpx;
	}

	.arrow-up.active {
		color: #00c896;
	}

	.arrow-down.active {
		color: #00c896;
	}
	.filter-icon {
		width: 28rpx;
		height: 28rpx;
		margin-left: 8rpx;
	}

	/* 内容区域 */
	.content {
		padding: 20rpx;
	}

	/* 无商品提示 */
	.wu {
		text-align: center;
		padding: 80rpx 40rpx;
		color: #999;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.wu image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	/* 商品列表 */
	.sea_list {
		width: 100%;
	}

	.displayflexa {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.product-link {
		width: 48%;
		margin-bottom: 20rpx;
	}

	.seali_inf {
		background-color: white;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
		padding: 10rpx;
	}

	.inf_img {
		width: 100%;
		height: 240rpx;
		background-color: #fff;
		background-size: contain !important;
		background-position: center !important;
		background-repeat: no-repeat !important;
		border-radius: 8rpx;
	}

	.inf_con {
		padding: 16rpx;
	}

	.goods-name {
		color: #333;
		line-height: 1.4;
		margin-bottom: 8rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		text-overflow: ellipsis;
		word-break: break-all;
		height: 72rpx;
	}

	.rebate-info {
		color: #6e6e6e;
		margin: 10rpx 0;
	}

	.rebate-info text {
		color: #6e6e6e;
	}

	.price-info {
		color: #ff9600;
		font-weight: 700;
		margin-top: -6rpx;
	}

	.price-info text {
		font-size: 30rpx;
	}

	/* 字体大小类 */
	.font12 {
		font-size: 24rpx;
	}

	.font14 {
		font-size: 28rpx;
	}

	.font15 {
		font-size: 30rpx;
	}

	/* 加载更多 */
	.more {
		text-align: center;
		padding: 40rpx;
		color: #999;
		font-size: 28rpx;
	}

	.pull_icon {
		margin-right: 10rpx;
	}

	/* 筛选面板弹窗 */
	.filter-popup {
		position: fixed;
		top: 0;
		right: 0;
		width: 75%;
		height: 100vh;
		background-color: white;
		z-index: 1000;
		transform: translateX(0);
		transition: transform 0.3s ease;
	}

	.filter-panel {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	/* 筛选面板头部 */
	.filter-header {
		display: flex;
		align-items: center;
		padding: 30rpx;
		background-color: #fff;
	}

	.filter-title {
		margin-left: 20rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	/* 筛选内容 */
	.filter-content {
		flex: 1;
		padding: 40rpx 30rpx;
		overflow-y: auto;
	}

	.filter-section {
		margin-bottom: 60rpx;
	}

	.section-title {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 30rpx;
		font-weight: bold;
	}

	/* 价格输入框 */
	.price-inputs {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
	}

	.price-input {
		flex: 1;
		height: 80rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		text-align: center;
	}

	.price-separator {
		margin: 0 30rpx;
		color: #999;
		font-size: 28rpx;
	}

	/* 筛选选项 */
	.filter-options {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.filter-option {
		padding: 16rpx 32rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 40rpx;
		font-size: 28rpx;
		color: #666;
		background-color: #f9f9f9;
	}

	.filter-option.active {
		background-color: #ff6b35;
		color: white;
		border-color: #ff6b35;
	}

	/* 品牌展开按钮 */
	.brand-expand {
		text-align: right;
		margin-bottom: 30rpx;
	}

	.brand-expand .expand-text {
		color: #ff6b35;
		font-size: 28rpx;
	}

	/* 底部按钮 */
	.filter-footer {
		display: flex;
		padding: 30rpx;
		border-top: 2rpx solid #f0f0f0;
		background-color: white;
	}

	.reset-btn {
		flex: 1;
		height: 88rpx;
		background-color: #f5f5f5;
		color: #666;
		border: none;
		border-radius: 44rpx;
		margin-right: 20rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	.confirm-btn {
		flex: 2;
		height: 88rpx;
		background-color: #ff6b35;
		color: white;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
	}

	/* 遮罩层 */
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}
</style>